<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>实践一下--JWT | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="每天一篇面试小知识  本篇着重介绍一下 JWT   写在前面 目前大部分的项目都逐渐从单体架构向着前后端分离的方向发展 这个时候就涉及到前后端数据之间的交互，传输问题了， JWT 闪亮登场！">
<meta property="og:type" content="article">
<meta property="og:title" content="实践一下--JWT">
<meta property="og:url" content="https://curry3035.gitee.io/posts/53148/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="每天一篇面试小知识  本篇着重介绍一下 JWT   写在前面 目前大部分的项目都逐渐从单体架构向着前后端分离的方向发展 这个时候就涉及到前后端数据之间的交互，传输问题了， JWT 闪亮登场！">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2021-08-17T13:00:00.000Z">
<meta property="article:modified_time" content="2022-05-26T18:17:06.259Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="进阶">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/53148/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '实践一下--JWT',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-27 02:17:06'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">实践一下--JWT</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-08-17T13:00:00.000Z" title="发表于 2021-08-17 21:00:00">2021-08-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-26T18:17:06.259Z" title="更新于 2022-05-27 02:17:06">2022-05-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%A1%86%E6%9E%B6/">框架</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>17分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="实践一下--JWT"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>每天一篇面试小知识</p>
</blockquote>
<p><strong>本篇着重介绍一下 JWT</strong></p>
<hr>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-08-18_01-52-58.png"></p>
<p><strong>写在前面</strong></p>
<p>目前大部分的项目都逐渐从单体架构向着前后端分离的方向发展</p>
<p>这个时候就涉及到前后端数据之间的交互，传输问题了，<font color=#008000> JWT</font> 闪亮登场！</p>
<span id="more"></span>

<h3 id="JWT-是什么？"><a href="#JWT-是什么？" class="headerlink" title="JWT 是什么？"></a>JWT 是什么？</h3><p><strong>基本概念</strong></p>
<p><code>JWT</code>全称是<code>JSON Web Token</code>，如果从字面上理解感觉是基于<code>JSON</code>格式用于网络传输的令牌。常见的场景如<code>HTTP</code>授权请求头参数和<code>URI</code>查询参数。</p>
<hr>
<h3 id="传统-Token-方式和-JWT"><a href="#传统-Token-方式和-JWT" class="headerlink" title="传统 Token 方式和 JWT"></a>传统 Token 方式和 JWT</h3><p><strong>传统 token 方式：</strong></p>
<p>用户登录成功后，服务端生成一个随机 token 给用户，并且在服务端(数据库或缓存)中保存一份 token，以后用户再来访问时需携带 token，服务端接收到 token 之后，去数据库或缓存中进行校验 token 的是否超时、是否合法。</p>
<p><strong>jwt 方式：</strong></p>
<p>用户登录成功后，服务端通过 jwt 生成一个随机 token 给用户（服务端无需保留token），以后用户再来访问时需携带 token，服务端接收到 token之后，通过 jwt 对 token 进行校验是否超时、是否合法。</p>
<hr>
<h3 id="JWT-的结构"><a href="#JWT-的结构" class="headerlink" title="JWT 的结构"></a>JWT 的结构</h3><p><strong>简单的举个荔枝</strong></p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-08-18_02-16-32.png"></p>
<p>在其紧凑形式中，<strong>JSON Web Tokens</strong> 由用点 ( <code>.</code>)分隔的三个部分组成，它们是：</p>
<ul>
<li>标题（header）【令牌头部，记录了整个令牌的类型和签名算法】</li>
<li>有效载荷（payload）【令牌负荷，记录了保存的主体信息，比如你要保存的用户信息就可以放到这里】</li>
<li>签名（signature）【令牌签名，按照头部固定的签名算法对整个令牌进行签名，该签名的作用是：保证令牌不被伪造和篡改】</li>
</ul>
<p>因此，JWT 通常如下所示。</p>
<figure class="highlight properties"><table><tr><td class="code"><pre><span class="line"><span class="attr">xxxxx.yyyyy.zzzzz</span>  =<span class="string">======&gt;  标题.有效载荷.签名</span></span><br></pre></td></tr></table></figure>

<p><strong>1、标题</strong></p>
<p>标头<em>通常</em>由两部分组成：令牌的类型，即 JWT，以及正在使用的签名算法，例如 HMAC SHA256 或 RSA。</p>
<p>例如：</p>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">&#123;</span></span><br><span class="line">  <span class="attr">&quot;alg&quot;</span><span class="punctuation">:</span> <span class="string">&quot;HS256&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;typ&quot;</span><span class="punctuation">:</span> <span class="string">&quot;JWT&quot;</span></span><br><span class="line"><span class="punctuation">&#125;</span></span><br></pre></td></tr></table></figure>

<p>然后，这个 JSON 被<strong>Base64Url</strong>编码以形成 JWT 的第一部分。</p>
<p><strong>2、有效载荷</strong></p>
<p>令牌的第二部分是负载，其中包含声明。声明是关于实体（通常是用户）和附加数据的声明。共有三种类型的声明：<em>注册声明</em>、<em>公共</em>声明和<em>私人</em>声明。</p>
<p>一个示例有效载荷可能是：</p>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">&#123;</span></span><br><span class="line">  <span class="attr">&quot;sub&quot;</span><span class="punctuation">:</span> <span class="string">&quot;1234567890&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;name&quot;</span><span class="punctuation">:</span> <span class="string">&quot;John Doe&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;admin&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">true</span></span></span><br><span class="line"><span class="punctuation">&#125;</span></span><br></pre></td></tr></table></figure>

<p>然后对有效负载进行<strong>Base64Url</strong>编码以形成 JSON Web 令牌的第二部分。</p>
<p><strong>3、签名</strong></p>
<p>要创建签名部分，您必须获取编码的标头、编码的有效载荷、秘密、标头中指定的算法，并对其进行签名。</p>
<p>例如，如果要使用 HMAC SHA256 算法，则签名将通过以下方式创建：</p>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line">HMACSHA256(</span><br><span class="line">  base64UrlEncode(header) + <span class="string">&quot;.&quot;</span> +</span><br><span class="line">  base64UrlEncode(payload)<span class="punctuation">,</span></span><br><span class="line">  secret)</span><br></pre></td></tr></table></figure>

<p>签名用于验证消息在此过程中没有更改，并且在使用私钥签名的令牌的情况下，它还可以验证 JWT 的发送者是它所说的那个人。</p>
<p><strong>4、放在一起</strong></p>
<p>输出是三个由点分隔的 Base64-URL 字符串，可以在 HTML 和 HTTP 环境中轻松传递，同时与基于 XML 的标准（如 SAML）相比更加紧凑。</p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-08-18_02-35-37.png"></p>
<hr>
<h3 id="JWT-的原理"><a href="#JWT-的原理" class="headerlink" title="JWT 的原理"></a>JWT 的原理</h3><p>JWT 的原理是，服务器认证以后，生成一个 JSON 对象，发回给用户，就像下面这样。</p>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line"><span class="punctuation">&#123;</span> </span><br><span class="line">    <span class="attr">&quot;姓名&quot;</span><span class="punctuation">:</span> <span class="string">&quot;张三&quot;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;角色&quot;</span><span class="punctuation">:</span> <span class="string">&quot;管理员&quot;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="attr">&quot;到期时间&quot;</span><span class="punctuation">:</span> <span class="string">&quot;2018年7月1日0点0分&quot;</span> </span><br><span class="line"><span class="punctuation">&#125;</span> </span><br></pre></td></tr></table></figure>

<p>以后，用户与服务端通信的时候，都要发回这个 JSON 对象。服务器完全只靠这个对象认定用户身份。为了防止用户篡改数据，服务器在生成这个对象的时候，会加上签名。</p>
<p><strong>服务器就不保存任何 session 数据了，也就是说，服务器变成无状态了，从而比较容易实现扩展。</strong></p>
<p><strong>区别</strong> </p>
<ol>
<li>session 存储在服务端占用服务器资源，而 JWT 存储在客户端</li>
<li> session 存储在 Cookie 中，存在伪造跨站请求伪造攻击的风险 </li>
<li>session 只存在一台服务器上，那么下次请求就必须请求这台服务器，不利于分布式应用 </li>
<li>存储在客户端的 JWT 比存储在服务端的 session 更具有扩展性</li>
</ol>
<hr>
<h3 id="JWT的认证流程图"><a href="#JWT的认证流程图" class="headerlink" title="JWT的认证流程图"></a>JWT的认证流程图</h3><p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-08-18_02-16-33.png"></p>
<p><strong>流程说明：</strong></p>
<ol>
<li>浏览器发起请求登陆，携带用户名和密码；</li>
<li>服务端验证身份，根据算法，将用户标识符打包生成 token;</li>
<li>服务器返回JWT信息给浏览器，JWT不包含敏感信息；</li>
<li>浏览器发起请求获取用户资料，把刚刚拿到的 token一起发送给服务器；</li>
<li>服务器发现数据中有 token，验明正身；</li>
<li>服务器返回该用户的用户资料；</li>
</ol>
<hr>
<h3 id="JSON-网络令牌如何工作"><a href="#JSON-网络令牌如何工作" class="headerlink" title="JSON 网络令牌如何工作"></a>JSON 网络令牌如何工作</h3><p>每当用户想要访问受保护的路由或资源时，用户代理应该发送 JWT，通常在使用<strong>Bearer</strong>模式的<strong>Authorization</strong>标头中。标题的内容应如下所示：</p>
<figure class="highlight properties"><table><tr><td class="code"><pre><span class="line"><span class="attr">Authorization</span>: <span class="string">Bearer &lt;token&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>Authorization</code>标头中的有效 JWT ，如果令牌在<code>Authorization</code>标头中发送，跨源资源共享 (CORS) 不会成为问题，因为它不使用 cookie。</p>
</blockquote>
<h3 id="JWT-的应用场景"><a href="#JWT-的应用场景" class="headerlink" title="JWT 的应用场景"></a>JWT 的应用场景</h3><ul>
<li><p><strong>Authorization (授权)</strong> </p>
<p> 这是使用JWT的最常见场景。一旦用户登录，后续每个请求都将包含 JWT，允许用户访问该令牌允许的路由、服务和资源。单点登录是现在广泛使用的 JWT 的一个特性，因为它的开销很小，并且可以轻松地跨域使用。</p>
</li>
<li><p><strong>Information Exchange (信息交换)</strong> </p>
<p>对于安全的在各方之间传输信息而言，JSON Web Tokens 无疑是一种很好的方式。因为 JWT 可以被签名，例如，用公钥/私钥对，你可以确定发送人就是它们所说的那个人。另外，由于签名是使用头和有效负载计算的，您还可以验证内容没有被篡改。</p>
</li>
</ul>
<hr>
<h3 id="JWT-测试"><a href="#JWT-测试" class="headerlink" title="JWT 测试"></a>JWT 测试</h3><h4 id="1、导入依赖"><a href="#1、导入依赖" class="headerlink" title="1、导入依赖"></a>1、导入依赖</h4><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/com.auth0/java-jwt --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.auth0<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>java-jwt<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.14.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2、生成token"><a href="#2、生成token" class="headerlink" title="2、生成token"></a>2、生成token</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *   常见的异常信息</span></span><br><span class="line"><span class="comment"> * - SignatureVerificationException   签名不一致异常</span></span><br><span class="line"><span class="comment"> * - TokenExpiredException            令牌过期异常</span></span><br><span class="line"><span class="comment"> * - AlgorirhmMismatchExceotion       算法不匹配异常</span></span><br><span class="line"><span class="comment"> * - InvalidClaimException            失效的payload异常</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="meta">@Log4j2</span></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="meta">@DisplayName(&quot;JWTTest 接口测试&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JWTTest</span> &#123;</span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="meta">@DisplayName(&quot;生成 token&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">creatToken</span><span class="params">()</span> &#123;</span><br><span class="line">        HashMap&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        map.put(<span class="string">&quot;typ&quot;</span>, <span class="string">&quot;JWT&quot;</span>);</span><br><span class="line">        map.put(<span class="string">&quot;alg&quot;</span>, <span class="string">&quot;HS256&quot;</span>);</span><br><span class="line">        <span class="type">Calendar</span> <span class="variable">instance</span> <span class="operator">=</span> Calendar.getInstance();</span><br><span class="line">        <span class="comment">// 20秒后令牌token失效</span></span><br><span class="line">        instance.add(Calendar.SECOND, <span class="number">5</span> * <span class="number">60</span>);</span><br><span class="line">        <span class="type">String</span> <span class="variable">token</span> <span class="operator">=</span> JWT.create()</span><br><span class="line">                .withHeader(map) <span class="comment">// header可以不写，因为默认值就是它</span></span><br><span class="line">                .withClaim(<span class="string">&quot;userId&quot;</span>, <span class="number">21</span>)  <span class="comment">//payload</span></span><br><span class="line">                .withClaim(<span class="string">&quot;username&quot;</span>, <span class="string">&quot;tom&quot;</span>)</span><br><span class="line">                .withExpiresAt(instance.getTime()) <span class="comment">// 指定令牌的过期时间</span></span><br><span class="line">                .sign(Algorithm.HMAC256(<span class="string">&quot;jsonwebtoken&quot;</span>));<span class="comment">//签名</span></span><br><span class="line"></span><br><span class="line">        log.info(token);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>生成结果</strong></p>
<figure class="highlight json"><table><tr><td class="code"><pre><span class="line">token<span class="punctuation">:</span>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsIm5hbWUiOiJqYW1lcyIsImV4cCI6MTYzMDM1NDU4Mn0.ubecr4PGlovbRggmfZBgoOnThtsSyykLyrcMiAmOaqY</span><br></pre></td></tr></table></figure>

<h4 id="3、根据令牌和签名解析数据"><a href="#3、根据令牌和签名解析数据" class="headerlink" title="3、根据令牌和签名解析数据"></a>3、根据令牌和签名解析数据</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Log4j2</span></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="meta">@DisplayName(&quot;JWTTest 接口测试&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JWTTest</span> &#123;</span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="meta">@DisplayName(&quot;根据令牌和签名解析数据&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">decryptionToken</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// 通过签名生成验证对象</span></span><br><span class="line">        <span class="type">JWTVerifier</span> <span class="variable">jwtVerifier</span> <span class="operator">=</span> JWT.require(Algorithm.HMAC256(<span class="string">&quot;jsonwebtoken&quot;</span>)).build();</span><br><span class="line">        <span class="type">String</span> <span class="variable">token</span> <span class="operator">=</span> <span class="string">&quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Mjk3NDEwNjQsInVzZXJJZCI6MjEsInVzZXJuYW1lIjoidG9tIn0._spam3Ix5AvASN857eUOSFzDnVmZwk754lCbv8p4VfE&quot;</span>;</span><br><span class="line">        <span class="type">DecodedJWT</span> <span class="variable">verify</span> <span class="operator">=</span> jwtVerifier.verify(token);</span><br><span class="line">        log.info(verify.getClaim(<span class="string">&quot;userId&quot;</span>));</span><br><span class="line">        log.info(verify.getClaim(<span class="string">&quot;username&quot;</span>));</span><br><span class="line">        log.info(<span class="string">&quot;令牌过期时间：&quot;</span> + verify.getExpiresAt());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>生成结果</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line">[           main] c.a.m.t.t.JWTTest                        : &quot;james&quot;</span><br><span class="line">[           main] c.a.m.t.t.JWTTest                        : &quot;123456&quot;</span><br><span class="line">[           main] c.a.m.t.t.JWTTest                        : 令牌过期时间：Tue Aug 31 04:16:22 CST 2021</span><br></pre></td></tr></table></figure>

<h4 id="4、常见的异常信息"><a href="#4、常见的异常信息" class="headerlink" title="4、常见的异常信息"></a>4、常见的异常信息</h4><figure class="highlight json"><table><tr><td class="code"><pre><span class="line">- SignatureVerificationException   签名不一致异常</span><br><span class="line">- TokenExpiredException            令牌过期异常</span><br><span class="line">- AlgorirhmMismatchExceotion       算法不匹配异常</span><br><span class="line">- InvalidClaimException            失效的payload异常</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="JWT-SpringBoot"><a href="#JWT-SpringBoot" class="headerlink" title="JWT + SpringBoot"></a>JWT + SpringBoot</h3><h4 id="1、导入依赖-1"><a href="#1、导入依赖-1" class="headerlink" title="1、导入依赖"></a>1、导入依赖</h4><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- spring-boot --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">exclusions</span>&gt;</span><span class="comment">&lt;!-- 去掉springboot默认配置 --&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">exclusion</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-logging<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;/<span class="name">exclusion</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;/<span class="name">exclusions</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- 引入log4j2依赖 --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-log4j2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-devtools<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!--MyBatis-Plus代码生成器需要的依赖，开始--&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- lombok --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- mysql --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.49<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- mybatis-plus --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="comment">&lt;!-- &lt;version&gt;3.2.0&lt;/version&gt;--&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.3.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- 代码生成器 --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-generator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.4.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- Velocity --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.velocity<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>velocity-engine-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--MyBatis-Plus代码生成器需要的依赖，结束--&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- swagger --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>io.springfox<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>springfox-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.0.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.github.xiaoymin<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>swagger-bootstrap-ui<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.9.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- druid --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>druid-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.21<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- https://mvnrepository.com/artifact/com.auth0/java-jwt --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.auth0<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>java-jwt<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.14.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!-- test --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2、Mybatis-Plus-自动生成"><a href="#2、Mybatis-Plus-自动生成" class="headerlink" title="2、Mybatis-Plus 自动生成"></a>2、Mybatis-Plus 自动生成</h4><p><strong>entity</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@EqualsAndHashCode(callSuper = false)</span></span><br><span class="line"><span class="meta">@TableName(&quot;user&quot;)</span></span><br><span class="line"><span class="meta">@ApiModel(value=&quot;User对象&quot;, description=&quot;InnoDB free: 10240 kB&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> <span class="keyword">implements</span> <span class="title class_">Serializable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">long</span> <span class="variable">serialVersionUID</span> <span class="operator">=</span> <span class="number">1L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;主键ID&quot;)</span></span><br><span class="line">    <span class="meta">@TableId(value = &quot;id&quot;, type = IdType.AUTO)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;姓名&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(&quot;name&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;密码&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(&quot;password&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;年龄&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(&quot;age&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;邮箱&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(&quot;email&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String email;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;创建时间&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(value = &quot;create_time&quot;, fill = FieldFill.INSERT)</span></span><br><span class="line">    <span class="keyword">private</span> Date createTime;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;更新时间&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(value = &quot;update_time&quot;, fill = FieldFill.INSERT_UPDATE)</span></span><br><span class="line">    <span class="keyword">private</span> Date updateTime;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;乐观锁&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(&quot;version&quot;)</span></span><br><span class="line">    <span class="meta">@Version</span></span><br><span class="line">    <span class="keyword">private</span> Integer version;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(value = &quot;逻辑删除&quot;)</span></span><br><span class="line">    <span class="meta">@TableField(&quot;remove_logic&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Integer removeLogic;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>controller</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Api(&quot;用户管理&quot;)</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/abc/user&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserService userService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用户登录</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation(&quot;用户登录&quot;)</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/login&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Result <span class="title function_">login</span><span class="params">(<span class="meta">@RequestParam(&quot;name&quot;)</span> String name, <span class="meta">@RequestParam(&quot;password&quot;)</span> String password)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> userService.login(name, password);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询所有用户</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation(&quot;查询所有用户&quot;)</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/query_all_list&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Result <span class="title function_">queryAllList</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> userService.queryAllList();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 验证 token 合法性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@ApiOperation(&quot;用户登录&quot;)</span></span><br><span class="line">    <span class="meta">@PostMapping(&quot;/verify&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> Result <span class="title function_">verify</span><span class="params">(<span class="meta">@RequestParam(&quot;token&quot;)</span> String token)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> userService.verify(token);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>service</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserService</span> <span class="keyword">extends</span> <span class="title class_">IService</span>&lt;User&gt; &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用户登录</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    Result <span class="title function_">login</span><span class="params">(String name, String password)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 验证 token 合法性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    Result <span class="title function_">verify</span><span class="params">(String token)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询所有用户</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    Result <span class="title function_">queryAllList</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>serviceImpl</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Log4j2</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserServiceImpl</span> <span class="keyword">extends</span> <span class="title class_">ServiceImpl</span>&lt;UserMapper, User&gt; <span class="keyword">implements</span> <span class="title class_">UserService</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 用户登录</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Result <span class="title function_">login</span><span class="params">(String name, String password)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;用户名：[&#123;&#125;]&quot;</span>, name);</span><br><span class="line">        log.info(<span class="string">&quot;密码：[&#123;&#125;]&quot;</span>, password);</span><br><span class="line">        Map&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            QueryWrapper&lt;User&gt; wrapper = <span class="keyword">new</span> <span class="title class_">QueryWrapper</span>&lt;&gt;();</span><br><span class="line">            wrapper.eq(<span class="string">&quot;name&quot;</span>, name).eq(<span class="string">&quot;password&quot;</span>, password);</span><br><span class="line">            <span class="type">User</span> <span class="variable">userInfo</span> <span class="operator">=</span> userMapper.selectOne(wrapper);</span><br><span class="line">            <span class="comment">// log.info(&quot;用户：[&#123;&#125;]&quot;, userInfo.toString());</span></span><br><span class="line">            <span class="comment">// 设置 payload 有效信息</span></span><br><span class="line">            Map&lt;String, String&gt; payload = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">            payload.put(<span class="string">&quot;name&quot;</span>, userInfo.getName());</span><br><span class="line">            payload.put(<span class="string">&quot;password&quot;</span>, userInfo.getPassword());</span><br><span class="line">            <span class="comment">// 生成jwt令牌</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">token</span> <span class="operator">=</span> JwtUtils.creatToken(payload);</span><br><span class="line">            map.put(<span class="string">&quot;name&quot;</span>, userInfo.getName());</span><br><span class="line">            map.put(<span class="string">&quot;password&quot;</span>, userInfo.getPassword());</span><br><span class="line">            map.put(<span class="string">&quot;token&quot;</span>, token);  <span class="comment">// 响应token</span></span><br><span class="line">            <span class="keyword">return</span> ResUtils.success(map);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            map.put(<span class="string">&quot;state&quot;</span>, <span class="literal">false</span>);</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>, e.getMessage());</span><br><span class="line">            <span class="keyword">return</span> ResUtils.failure(map);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 验证 token 合法性</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Result <span class="title function_">verify</span><span class="params">(String token)</span> &#123;</span><br><span class="line">        log.info(<span class="string">&quot;当前token为：[&#123;&#125;]&quot;</span>, token);</span><br><span class="line">        Map&lt;String, Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 验证令牌</span></span><br><span class="line">            JwtUtils.verifyGetTokenInfo(token);</span><br><span class="line">            map.put(<span class="string">&quot;state&quot;</span>, <span class="literal">true</span>);</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;请求成功&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> ResUtils.success(map);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (SignatureVerificationException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;无效签名！&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> ResUtils.failure(map);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (TokenExpiredException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;token过期&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> ResUtils.failure(map);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (AlgorithmMismatchException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;算法不一致&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> ResUtils.failure(map);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;token无效！&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> ResUtils.failure(map);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询所有用户</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Result <span class="title function_">queryAllList</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> ResUtils.success(userMapper.selectList(<span class="literal">null</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>mapper</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserMapper</span> <span class="keyword">extends</span> <span class="title class_">BaseMapper</span>&lt;User&gt; &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>mapper.xml</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span> <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span> <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.ase.mybatis.abc.mapper.UserMapper&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="3、封装-JWT-工具类"><a href="#3、封装-JWT-工具类" class="headerlink" title="3、封装 JWT 工具类"></a>3、封装 JWT 工具类</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JwtUtils</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 设置加密的私钥</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">String</span> <span class="variable">SING</span> <span class="operator">=</span> <span class="string">&quot;jsonwebtoken&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1、生成 token  header.payload.singature 【加密后发送给客户端】</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">creatToken</span><span class="params">(Map&lt;String, String&gt; map)</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">Calendar</span> <span class="variable">instance</span> <span class="operator">=</span> Calendar.getInstance();</span><br><span class="line">        <span class="comment">// 默认7天过期</span></span><br><span class="line">        instance.add(Calendar.DATE, <span class="number">7</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建jwt builder</span></span><br><span class="line">        JWTCreator.<span class="type">Builder</span> <span class="variable">builder</span> <span class="operator">=</span> JWT.create();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// payload</span></span><br><span class="line">        map.forEach((k, v) -&gt; &#123;</span><br><span class="line">            builder.withClaim(k, v);</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="type">String</span> <span class="variable">token</span> <span class="operator">=</span> builder.withExpiresAt(instance.getTime())  <span class="comment">//指定令牌过期时间</span></span><br><span class="line">                .sign(Algorithm.HMAC256(SING));  <span class="comment">// sign</span></span><br><span class="line">        <span class="keyword">return</span> token;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 2、验证 token 合法性, 并获取 token 信息方法 【客户端请求时 header 中携带, 如果客户端携带的 token 是合法的, 则获取有效载荷中的数据】</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> DecodedJWT <span class="title function_">verifyGetTokenInfo</span><span class="params">(String token)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> JWT.require(Algorithm.HMAC256(SING)).build().verify(token);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="4、创建拦截器"><a href="#4、创建拦截器" class="headerlink" title="4、创建拦截器"></a>4、创建拦截器</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JwtInterceptors</span> <span class="keyword">implements</span> <span class="title class_">HandlerInterceptor</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">preHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        Map&lt;String,Object&gt; map = <span class="keyword">new</span> <span class="title class_">HashMap</span>&lt;&gt;();</span><br><span class="line">        <span class="comment">// 获取请求头中令牌</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">token</span> <span class="operator">=</span> request.getHeader(<span class="string">&quot;Authorization&quot;</span>);</span><br><span class="line">        <span class="comment">// 要删除的字符串结束位置</span></span><br><span class="line">        <span class="type">int</span> end;</span><br><span class="line">        <span class="comment">// 正规表达式</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">regPattern</span> <span class="operator">=</span> <span class="string">&quot;Bearer &quot;</span>;</span><br><span class="line">        <span class="type">Pattern</span> <span class="variable">pattern</span> <span class="operator">=</span> Pattern.compile(regPattern, Pattern.CASE_INSENSITIVE);</span><br><span class="line">        <span class="comment">// 去掉原始字符串开头位置的指定字符</span></span><br><span class="line">        <span class="type">Matcher</span> <span class="variable">matcher</span> <span class="operator">=</span> pattern.matcher(token);</span><br><span class="line">        <span class="keyword">if</span> (matcher.lookingAt()) &#123;</span><br><span class="line">            end = matcher.end();</span><br><span class="line">            token = token.substring(end);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(token);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 验证令牌</span></span><br><span class="line">            JwtUtils.verifyGetTokenInfo(token);</span><br><span class="line">            map.put(<span class="string">&quot;state&quot;</span>, <span class="literal">true</span>);</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>, <span class="string">&quot;请求成功&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;  <span class="comment">// 放行请求</span></span><br><span class="line">        &#125; <span class="keyword">catch</span> (SignatureVerificationException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;无效签名！&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (TokenExpiredException e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;token过期&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (AlgorithmMismatchException e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;算法不一致&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            map.put(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;token无效！&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        map.put(<span class="string">&quot;state&quot;</span>,<span class="literal">false</span>);  <span class="comment">// 设置状态</span></span><br><span class="line">        <span class="comment">// 将map以json的形式响应到前台  map --&gt; json  (jackson)</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectMapper</span>().writeValueAsString(map);</span><br><span class="line">        response.setContentType(<span class="string">&quot;application/json;charset=UTF-8&quot;</span>);</span><br><span class="line">        response.getWriter().println(json);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="5、定制拦截器规则"><a href="#5、定制拦截器规则" class="headerlink" title="5、定制拦截器规则"></a>5、定制拦截器规则</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">InterceptorConfig</span> <span class="keyword">implements</span> <span class="title class_">WebMvcConfigurer</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">addInterceptors</span><span class="params">(InterceptorRegistry registry)</span> &#123;</span><br><span class="line">        <span class="comment">//注册添加拦截器 JwtInterceptors</span></span><br><span class="line">        registry.addInterceptor(<span class="keyword">new</span> <span class="title class_">JwtInterceptors</span>())</span><br><span class="line">                .addPathPatterns(<span class="string">&quot;/**&quot;</span>)  <span class="comment">// 其他接口token验证 【用于设置拦截器的过滤路径规则；addPathPatterns(&quot;/**&quot;)对所有请求都拦截】</span></span><br><span class="line">                .excludePathPatterns(<span class="string">&quot;/abc/user/login&quot;</span>);  <span class="comment">// 登录是所有用户都放行的 【用于设置不需要拦截的过滤规则】</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="6、请求头验证token"><a href="#6、请求头验证token" class="headerlink" title="6、请求头验证token"></a>6、请求头验证token</h4><p><strong>登录获取 token</strong></p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-08-24_04-38-25.png"></p>
<p><strong>编写脚本将 token 存在环境变量中，即时更新</strong></p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-08-24_04-36-52.png"></p>
<p><strong>请求携带 token 通过验证得到返回结果</strong></p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-08-24_04-37-20.png"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/53148/">https://curry3035.gitee.io/posts/53148/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%BF%9B%E9%98%B6/">进阶</a><a class="post-meta__tags" href="/tags/spring/">spring</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/53731/" title="实用链接"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">实用链接</div></div></a></div><div class="next-post pull-right"><a href="/posts/51171/" title="实践一下--MyBatisPlus"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">实践一下--MyBatisPlus</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/55119/" title="每日一面--Files工具类"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-01</div><div class="title">每日一面--Files工具类</div></div></a></div><div><a href="/posts/34600/" title="面试一下--JUC入门"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-09-10</div><div class="title">面试一下--JUC入门</div></div></a></div><div><a href="/posts/11315/" title="实践一下--Spring Security"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-01</div><div class="title">实践一下--Spring Security</div></div></a></div><div><a href="/posts/40042/" title="每日一面--反射"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-01</div><div class="title">每日一面--反射</div></div></a></div><div><a href="/posts/56511/" title="实践一下--MySQL 优化"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-04</div><div class="title">实践一下--MySQL 优化</div></div></a></div><div><a href="/posts/27951/" title="学习--ElasticSearch"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-29</div><div class="title">学习--ElasticSearch</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT-%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">JWT 是什么？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BC%A0%E7%BB%9F-Token-%E6%96%B9%E5%BC%8F%E5%92%8C-JWT"><span class="toc-number">2.</span> <span class="toc-text">传统 Token 方式和 JWT</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT-%E7%9A%84%E7%BB%93%E6%9E%84"><span class="toc-number">3.</span> <span class="toc-text">JWT 的结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT-%E7%9A%84%E5%8E%9F%E7%90%86"><span class="toc-number">4.</span> <span class="toc-text">JWT 的原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT%E7%9A%84%E8%AE%A4%E8%AF%81%E6%B5%81%E7%A8%8B%E5%9B%BE"><span class="toc-number">5.</span> <span class="toc-text">JWT的认证流程图</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JSON-%E7%BD%91%E7%BB%9C%E4%BB%A4%E7%89%8C%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C"><span class="toc-number">6.</span> <span class="toc-text">JSON 网络令牌如何工作</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT-%E7%9A%84%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-number">7.</span> <span class="toc-text">JWT 的应用场景</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT-%E6%B5%8B%E8%AF%95"><span class="toc-number">8.</span> <span class="toc-text">JWT 测试</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81%E5%AF%BC%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="toc-number">8.1.</span> <span class="toc-text">1、导入依赖</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81%E7%94%9F%E6%88%90token"><span class="toc-number">8.2.</span> <span class="toc-text">2、生成token</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%E3%80%81%E6%A0%B9%E6%8D%AE%E4%BB%A4%E7%89%8C%E5%92%8C%E7%AD%BE%E5%90%8D%E8%A7%A3%E6%9E%90%E6%95%B0%E6%8D%AE"><span class="toc-number">8.3.</span> <span class="toc-text">3、根据令牌和签名解析数据</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%E3%80%81%E5%B8%B8%E8%A7%81%E7%9A%84%E5%BC%82%E5%B8%B8%E4%BF%A1%E6%81%AF"><span class="toc-number">8.4.</span> <span class="toc-text">4、常见的异常信息</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT-SpringBoot"><span class="toc-number">9.</span> <span class="toc-text">JWT + SpringBoot</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81%E5%AF%BC%E5%85%A5%E4%BE%9D%E8%B5%96-1"><span class="toc-number">9.1.</span> <span class="toc-text">1、导入依赖</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81Mybatis-Plus-%E8%87%AA%E5%8A%A8%E7%94%9F%E6%88%90"><span class="toc-number">9.2.</span> <span class="toc-text">2、Mybatis-Plus 自动生成</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%E3%80%81%E5%B0%81%E8%A3%85-JWT-%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-number">9.3.</span> <span class="toc-text">3、封装 JWT 工具类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%E3%80%81%E5%88%9B%E5%BB%BA%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-number">9.4.</span> <span class="toc-text">4、创建拦截器</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5%E3%80%81%E5%AE%9A%E5%88%B6%E6%8B%A6%E6%88%AA%E5%99%A8%E8%A7%84%E5%88%99"><span class="toc-number">9.5.</span> <span class="toc-text">5、定制拦截器规则</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#6%E3%80%81%E8%AF%B7%E6%B1%82%E5%A4%B4%E9%AA%8C%E8%AF%81token"><span class="toc-number">9.6.</span> <span class="toc-text">6、请求头验证token</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>